package network

import (
	//"log"
	"reflect"
)

type EventPipe interface {
	AddQueue() EventQueue
	Start()
}

type evPipe struct {
	qArr    []*evQueuc
	arrLock bool
}

func (self *evPipe) AddQueue() EventQueue {
	if self.arrLock {
		panic("pipe already start, can not addqueue any more.")
	}

	q := newEventQueue()
	self.qArr = append(self.qArr, q)
	return q
}

func (self *evPipe) Start() {
	self.arrLock = true

	go func() {
		cases := make([]reflect.SelectCase, len(self.qArr))
		for i, q := range self.qArr {
			cases[i] = reflect.SelectCase{
				Dir:  reflect.SelectRecv,
				Chan: reflect.ValueOf(q.queue),
			}
		}

		for {
			if idx, val, ok := reflect.Select(cases); ok {
				self.qArr[idx].CallData(val.Interface())
			}
		}
	}()
}

func NewEventPipe() EventPipe {
	return &evPipe{
		qArr:    make([]*evQueuc, 0),
		arrLock: false,
	}
}
